﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Libu=LibUpdate;
using System.Diagnostics;
using System.Threading;

namespace Dome_Update
{
    public partial class UpdatePanle : Form
    {
        Libu.UpdateControl con;
        private string[] cmd;
        
        //命令参数
        public string[] Cmd
        {
            get { return cmd; }
            set { cmd = value; }
        }
        public UpdatePanle()
        {
            InitializeComponent();
            Libu.UpdateConfig uconfig = new LibUpdate.UpdateConfig();
            con = new Libu.UpdateControl(uconfig);
            uconfig.ApplictionPath=Application.StartupPath;
            uconfig.ServerPath = Libu.UpdateVerXML.XMLtoBase(Application.StartupPath + "\\clientversion.xml");
            uconfig.TautologyCount = 3;
            uconfig.DownProviderType = Libu.DownProviderType.Http;
           con.VersionCheckChange+=new LibUpdate.VersionCheckChangedHandler(con_VersionCheckChange);
            con.VersionStatusChange+=new LibUpdate.VersionUpdateStatusChangedHandler(con_VersionStatusChange);
            con.DownStatuesChange+=new LibUpdate.FileDownStatusChangedHandler(con_DownStatuesChange);
            con.DownProgresChange+=new LibUpdate.FileDownProgressChangedHandler(con_DownProgresChange);
            con.ActionInfo+=new LibUpdate.ActionEventHandler(con_ActionInfo);
            
           
        }

        /// <summary>
        /// 绑定文件；列表
        /// </summary>
        /// <param name="ver"></param>
        private void bind_ver_list(Libu.Version ver)
        {
            listView1.Items.Clear();

            downinfo.Text = "当前更新版本："+ ver.VersionNum.ToString(3);
            listView1.BeginUpdate();
            for (int i = 0; i < ver.FileList.Count; i++)
            {
                Libu.File f=ver.FileList[i];
                
                if (f.Type != Libu.FileType.Directory)
                {
                    ListViewItem item = new ListViewItem(f.FileName);
                    item.SubItems.Add((f.Size / 1024).ToString() + "K");
                    item.SubItems[1].Tag = f.Size;
                    item.SubItems.Add("0");
                    item.SubItems.Add("排队中");
                    item.SubItems.Add("");

                    item.Tag = i;
                  
                    listView1.Items.Add(item);
                }
            }
            
            listView1.EndUpdate();
            Application.DoEvents();
        }

        /// <summary>
        /// 根据文件索引 获得列表中列表项
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        private ListViewItem GetListFileIndex(int index)
        {
            ListViewItem item=null;
            for (int i = 0; i < listView1.Items.Count; i++)
            {
                if ((int)listView1.Items[i].Tag == index)
                {
                    item = listView1.Items[i];
                    break;
                }
            }

            return item;
        }

        /// <summary>
        /// 版本检查状态
        /// </summary>
        /// <param name="e"></param>
        private void con_VersionCheckChange(Libu.VersionCheckEventArgs e)
        {
            if (e.NewVersion)
            {
                WaitCallback wc = new WaitCallback(this.StateUpdateSoft);
                ThreadPool.QueueUserWorkItem(wc,"");

             
            }
            else
            {
                if (DialogResult.Yes == MessageBox.Show("当前系统已经是最新版本,是否退出升级?", "提示", MessageBoxButtons.YesNo)) 
                { Application.Exit(); }
            }
        }

        private void StateUpdateSoft(object o)
        {
            con.UpdateSoft();
        }
        
        /// <summary>
        /// 版本更新状态
        /// </summary>
        /// <param name="e"></param>
        private void con_VersionStatusChange(Libu.VersionUpdateStatusChangedEvent e)
        {
            if (this.Disposing || this.IsDisposed)
            {
                return;
            }
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<Libu.VersionUpdateStatusChangedEvent>(this.con_VersionStatusChange), e);
            }
            else
            {
                if (e.State == Libu.VersionDownState.BegionVersionUpdate)
                {
                    bind_ver_list(e.Version);
                }
                else if (e.State == Libu.VersionDownState.EndVersionUpdate)
                {
                    if (con.Colophon.NextVer(e.Version).VersionNum == new System.Version("0.0.0.0"))
                    {
                        if (DialogResult.Yes == MessageBox.Show("全部更新完成，是否退出升级程序并打开业务系统", "提示", MessageBoxButtons.YesNo))
                        {
                            StateMainExe();
                            Application.Exit();
                        }
                    }
                }
                else if (e.State == Libu.VersionDownState.Err)
                { 
                     MessageBox.Show(e.Version.VersionNum.ToString()+"版本更新失败！请检查网络或联系升级服务器管理员。", "提示");   
                }
                else if (e.State == Libu.VersionDownState.EndDown && e.Version.UpdateGoal==Libu.UpdateGoal.UpdatePro)
                { //更新自己
                    Update_me();
                }
                else if (e.State == Libu.VersionDownState.EndDown && e.Version.UpdateGoal == Libu.UpdateGoal.MainPro)
                { //下载完成后，需要更新主程序，则需要最主程序进行判断，
                    if (Get_Pro("FDSECU"))
                    {
                        if (MessageBox.Show("业务系统未关闭，请关闭主程序系统，主程序关闭后，点击【确定】，不更新系统则点击【取消】!", "提示", MessageBoxButtons.OKCancel) == DialogResult.OK)
                        { //循环判断
                            con_VersionStatusChange(e);
                        }
                        else
                        {
                            con.CloseUpdate = true;
                        }

                    }
                  
                }
            }
        }

        /// <summary>
        /// 下载状态响应
        /// </summary>
        private void con_DownStatuesChange(Libu.FileDownStatusChangedEvent e)
        {
            if (this.Disposing || this.IsDisposed)
            {
                return;
            }

            if (this.InvokeRequired)
            {
                this.Invoke(new Action<Libu.FileDownStatusChangedEvent>(this.con_DownStatuesChange), e);
            }
            else
            {
                ListViewItem listItem = GetListFileIndex(e.FileIndex);
                if (listItem != null)
                {
                    switch (e.State)
                    {
                        case Libu.FileDownState.Open:
                            listItem.SubItems[3].Text = "开始";
                            listItem.SubItems[2].Text = "0";
                            break;
                        case Libu.FileDownState.Again:
                            listItem.SubItems[3].Text = "重试"+e.File.TautologyCount+"次";
                            listItem.SubItems[2].Text = "0";

                            break;
                        case Libu.FileDownState.Down:
                            listItem.SubItems[3].Text = "下载中";
                            break;
                        case Libu.FileDownState.End:
                            listItem.SubItems[3].Text = "成功";
                            listItem.SubItems[2].Text = "100";
                            listItem.SubItems[4].Text = "等待";
                            break;
                        case Libu.FileDownState.Error:
                            listItem.SubItems[3].Text = "失败";
                            break;
                    }
                }
                if (e.State == Libu.FileDownState.Error && e.File.Type == Libu.FileType.UpdateInfoFile)
                {
                    MessageBox.Show("无法连接到服务器，不能获得最新版本信息。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            Application.DoEvents();
        }
        

        /// <summary>
        /// 下载进度
        /// </summary>
        /// <param name="e"></param>
        private void con_DownProgresChange(Libu.FileDownProgressChangedEvent e)
        {
            if (this.Disposing || this.IsDisposed)
            {
                return;
            }
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<Libu.FileDownProgressChangedEvent>(this.con_DownProgresChange), e);
            }
            else
            {
                ListViewItem listItem = GetListFileIndex(e.FileIndex);
                if (listItem != null)
                {
                        listItem.SubItems[2].Text = e.Progrees.ToString();
                        Application.DoEvents();
                }
            }
        }
        //更新相应
        private void con_ActionInfo(Libu.ActionEventArgs e)
        {
            if (this.Disposing || this.IsDisposed)
            {
                return;
            }
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<Libu.ActionEventArgs>(this.con_ActionInfo), e);
            }
            else
            {
                ListViewItem listItem = GetListFileIndex(e.FileIndex);
                if (listItem != null)
                {
                    if (e.ActionState == Libu.FileActionState.End)
                    {
                        listItem.SubItems[4].Text = "完成";
                    }//文件更新失败！
                    else if (Libu.FileActionState.Error == e.ActionState)
                    {
                        listItem.SubItems[4].Text = "失败";
                    }
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {

            WaitCallback wc = new WaitCallback(this.CheckVersion);
            ThreadPool.QueueUserWorkItem(wc, "");
     
        }
        private void CheckVersion(object o)
        {
            con.CheckVersion();
        }


        /// <summary>
        /// 启动业务系统
        /// </summary>
        private void StateMainExe()
        {
            if (System.IO.File.Exists(Application.StartupPath + "\\test.exe"))
            {
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo = new System.Diagnostics.ProcessStartInfo(Application.StartupPath + "\\test.exe");
                p.Start();
            }
        }

        /// <summary>
        /// 更新自己
        /// </summary>
        private void Update_me()
        {
            try
            {
                if (System.IO.File.Exists(Application.StartupPath + "\\Updateme.exe"))
                {
                    System.Diagnostics.Process p = new System.Diagnostics.Process();
                    p.StartInfo = new System.Diagnostics.ProcessStartInfo(Application.StartupPath + "\\Updateme.exe", "update");
                    p.Start();
                }
            }
            catch
            { }
            finally
            {
                Application.Exit();
            }
        }

    
        string cmd_str;
        private void UpdatePanle_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < cmd.Length; i++) {
                cmd_str = cmd[i];
                //主程序已经下载过服务器版本文件了。
                if (cmd_str.ToUpper() == "UPDATE") {
                    button2_Click(null, null);
                }
            }
        }

        /// <summary>
        /// 检测是否有该进程
        /// </summary>
        /// <param name="pro_name">进程名称</param>
        /// <returns></returns>
        private bool Get_Pro(string pro_name)
        {
            Process[] myProcesses = Process.GetProcesses();
            foreach (Process myProcess in myProcesses)
            {
                if (myProcess.ProcessName.ToUpper() == pro_name.ToUpper())
                {
                    return true;
                }
            }
                return false;
        }
    }
}
